<template>
  <div class="account-setting">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="姓名" prop="username" style="width: 400px;">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password" style="width: 400px;">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import { changeUserInfoById, getUserDetailById } from '@/api/user'
export default {
  data() {
    return {
      id: this.$route.params.id,
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.getUserinfo()
  },

  methods: {
    // 获取员工基本信息
    async getUserinfo() {
      const { data } = await getUserDetailById(this.id)
      this.ruleForm = data
      this.ruleForm.password = ''
    },
    // 清空
    resetForm() {
      this.getUserinfo()
      this.$refs.ruleForm.clearValidate()
    },
    // 提交修改用户名密码
    submitForm() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          const res = await changeUserInfoById(this.id, this.ruleForm)
          if (res.success) {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.getUserinfo()
          }
        } else {
          this.$message({
            message: '请检查输入内容',
            type: 'warning'
          })
          return false
        }
      })
    }
  }
}

</script>

<style>

</style>
